//
//  MBSpaceNewsViewController.m
//  MiBaoTu
//
//  Created by admin on 16/9/20.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBSpaceNewsDetailViewController.h"

#import "MBSpaceNewsDetailCell.h"
#import "EmojiView.h"

@interface MBSpaceNewsDetailViewController ()<UITableViewDataSource,UITableViewDelegate,MBSpaceNewsDetailCellDelegate,UITextFieldDelegate,EmojiViewDelegate> {
    UITableView                 *_tableView;
    NSMutableArray              *_mutArr;
    NSMutableArray              *_mutHeightArr;
    
    UIView                      *_inputView;
    UITextField                 *_inputField;
    UIView                      *_showderView;
    UIButton                    *sureBt;
    float                       inputTime;
    
    MBSpaceNewsDetailCell         *_selectCell;
    NSInteger                   selectIndex;//测试
    NSMutableDictionary         *_replyMutDic;
    int                         page;
    
    UIButton                    *emojiBt;
    EmojiView                   *_emojiView;
}

@end

@implementation MBSpaceNewsDetailViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self registerForKeyboardNotifications];
    if (ISIPAD) {
        [self onUpdateUIForView:self.orientation];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self removeForkeyboardNotifications];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _mutArr = [[NSMutableArray alloc]initWithArray:_dataArr];
    selectIndex = -1;
    _replyMutDic = [[NSMutableDictionary alloc]init];
    page = 1;
    _mutHeightArr = [[NSMutableArray alloc]init];
    // Do any additional setup after loading the view.
    [self setTitleView:@"全部评论"];
    [self setBackItem];
    
   [self setRightPlayerItem];
    
    [self onCreateUI];
    
}

#pragma mark - Actions
#pragma mark - UI
- (void)onCreateUI
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.backgroundView = nil;
    [self.view addSubview:_tableView];
    [_tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(onLoadNew)];
    [_tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(onLoadMore)];
    if (_isFormMyNews == YES) {
        [self onLoadNew];
    } else {
        //高度获取
        [self onLoadDataForHeight];
    }
    
    //键盘
    _inputView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 40)];
    _inputView.backgroundColor = UIColorFromHex(0xf5f5f5);
    _inputView.hidden = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:_inputView];
    
    emojiBt = [UIButton buttonWithType:UIButtonTypeCustom];
    emojiBt.backgroundColor = [UIColor clearColor];
    emojiBt.frame = CGRectMake(0, 0, 50, _inputView.height);
    [emojiBt setImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateNormal];
    [emojiBt setImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateNormal];
    [emojiBt setImageEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 5)];
    [emojiBt addTarget:self action:@selector(onSelectEmojiAction:) forControlEvents:UIControlEventTouchUpInside];
    [_inputView addSubview:emojiBt];
    
    _inputField = [[UITextField alloc]initWithFrame:CGRectMake(50, 5, _inputView.width-50-50, 30)];
    _inputField.backgroundColor = [UIColor whiteColor];
    _inputField.placeholder = @"填写评论";
    _inputField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _inputField.delegate = self;
    [_inputField setValue:[UIFont systemFontOfSize:13]forKeyPath:@"_placeholderLabel.font"];
    _inputField.font = [UIFont systemFontOfSize:13];
    [_inputField resignFirstResponder];
    [_inputView addSubview:_inputField];
    
    sureBt = [UIButton buttonWithType:UIButtonTypeCustom];
    sureBt.backgroundColor = [UIColor clearColor];
    sureBt.frame = CGRectMake(_inputView.width - 50, 0, 50, _inputView.height);
    [sureBt setTitle:@"回复" forState:UIControlStateNormal];
    [sureBt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    sureBt.titleLabel.font = [UIFont systemFontOfSize:13.f];
    [sureBt addTarget:self action:@selector(onSelectSureAction) forControlEvents:UIControlEventTouchUpInside];
    [_inputView addSubview:sureBt];
    
    _showderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 216 - 40)];
    _showderView.backgroundColor = [UIColorFromHex(0x000000) colorWithAlphaComponent:.2];
    _showderView.hidden = YES;
    _showderView.userInteractionEnabled = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:_showderView];
    
    //表情
    _emojiView = [[EmojiView alloc]init];
    _emojiView.delegate = self;
    [[UIApplication sharedApplication].keyWindow addSubview:_emojiView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onTapHideInputAction)];
    [_showderView addGestureRecognizer:tap];
}

- (void)onUpdateUIForView:(UIDeviceOrientation)orientation
{
    _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    _inputView.frame = CGRectMake(0, (_inputView.isHidden?_tableView.height:_inputView.top), SCREEN_WIDTH, 40);
    _inputField.frame = CGRectMake(10, 5, _inputView.width-60, 30);
    sureBt.frame = CGRectMake(_inputView.width - 50, 0, 50, _inputView.height);
    _showderView.frame = CGRectMake(0, 0, SCREEN_WIDTH, _inputView.top);
    [_tableView reloadData];
}

#pragma mark - 加载数据
- (void)onLoadNew
{
    if (_isFormMyNews == YES) {
        page = 1;
        [self onLoadData];
    } else {
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
    }
}

- (void)onLoadMore
{
    if (_isFormMyNews == YES) {
        ++page;
        [self onLoadData];
    } else {
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
    }
}

- (void)onLoadData
{
    NSNumber *UserID=  [UserManager standerDefult].userModel.UserID;
    
    if ([_dataDic.allKeys containsObject:@"CommentType"]) {
        
        NSString *url;
        if ([[_dataDic objectForKey:@"CommentType"] intValue] == 1) {
            //亲子秀
            url = [NSString stringWithFormat:FAMILYSHOW_SHOW_INFO_URL_PATH,[_dataDic objectForKey:@"ShowID"],UserID,UserID,[NSNumber numberWithInt:page]];
        } else if ([[_dataDic objectForKey:@"CommentType"] intValue] == 2) {
            //帖子
            url = [NSString stringWithFormat:FORUM_DETAIL_INFO_URL_PATH,[_dataDic objectForKey:@"ForumID"],[NSNumber numberWithInt:page]];
        }
        
        [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(id json) {
            
            [_tableView.header endRefreshing];
            [_tableView.footer endRefreshing];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if ([json[@"ret_code"] integerValue]==0) {
                NSArray *arr = json[@"data"];
                if (page == 1) {
                    [_mutArr removeAllObjects];
                }
                [self onSetUpReplyData:arr];
                
            }
            [_tableView  reloadData];
        } failure:^(NSError *error) {
            
            [_tableView.header endRefreshing];
            [_tableView.footer endRefreshing];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
        }];
    }
    
}

//调整返回数据
- (void)onSetUpReplyData:(NSArray *)arr
{
    //数据调整
    for (NSDictionary *dictionary in arr) {
        NSArray *array = [dictionary objectForKey:@"ReplyInfo"];
        if ([array isKindOfClass:[NSArray class]]) {
            if (array.count > 0) {
                //存有回复内容,先存评论内容
                NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:dictionary];
                [mutDic setObject:@{} forKey:@"ReplyInfo"];
                [_mutArr addObject:mutDic];
                
                for (NSDictionary *dic in array) {
                    NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:dictionary];
                    [mutDic setObject:dic forKey:@"ReplyInfo"];
                    [_mutArr addObject:mutDic];
                }
            } else {
                //没有回复内容
                NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:dictionary];
                [mutDic setObject:@{} forKey:@"ReplyInfo"];
                [_mutArr addObject:mutDic];
            }
        } else {
            //没有回复内容
            NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:dictionary];
            [mutDic setObject:@{} forKey:@"ReplyInfo"];
            [_mutArr addObject:mutDic];
        }
    }
    
    //高度获取
    [self onLoadDataForHeight];
}

//高度获取
- (void)onLoadDataForHeight
{
    [_mutHeightArr removeAllObjects];
    
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc]init];
    paragraph.lineSpacing = 6*PERCEN;
    
    for (NSDictionary *dic in _mutArr) {
        NSDictionary *ReplyInfo = [dic objectForKey:@"ReplyInfo"];
        CGFloat contentHiehgt = 0;
        if ([ReplyInfo isKindOfClass:[NSDictionary class]]) {
            if (ReplyInfo.allKeys.count == 0) {
                //评论
                NSString *content = [[NSString stringWithFormat:@"%@",[dic objectForKey:@"Content"]] replaceUnicode];
                
                NSMutableAttributedString *mutAttributing = [[NSMutableAttributedString alloc]initWithString:content];
                [mutAttributing addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, content.length)];
                [mutAttributing addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.] range:NSMakeRange(0, content.length)];
                
                contentHiehgt = [mutAttributing boundingRectWithSize:CGSizeMake((ISIPAD?SCREEN_WIDTH-920*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):SCREEN_WIDTH-50*PERCEN), 1000) options:1|2 context:nil].size.height;
            } else {
                //回复
                //内容
                NSString *comment = [[NSString stringWithFormat:@"%@",[ReplyInfo objectForKey:@"ReplyCont"]] replaceUnicode];
                NSString *str1 = @"回复";
                NSString *str2 = [NSString stringWithFormat:@"%@",[ReplyInfo objectForKey:@"RepliedName"]];
                NSString *content = [NSString stringWithFormat:@"%@%@: %@",str1,str2,comment];
                
                NSMutableAttributedString *mutAttributing = [[NSMutableAttributedString alloc]initWithString:content];
                [mutAttributing addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, content.length)];
                [mutAttributing addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.] range:NSMakeRange(0, content.length)];
                
                contentHiehgt = [mutAttributing boundingRectWithSize:CGSizeMake((ISIPAD?SCREEN_WIDTH-920*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):SCREEN_WIDTH-50*PERCEN), 1000) options:1|2 context:nil].size.height;
            }
            
            //总高度
            contentHiehgt = 20*PERCEN+40+12*PERCEN+contentHiehgt+5;
            [_mutHeightArr addObject:[NSNumber numberWithFloat:contentHiehgt]];
        }
    }
}

#pragma mark - 方法
//进入播放器
- (void)onSelectItemForWork
{
    [self onPlayMusic];
}

//键盘相关
- (void)registerForKeyboardNotifications
{
    //使用NSNotificationCenter 鍵盤出現時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShow:)
     
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    //使用NSNotificationCenter 鍵盤隐藏時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    
}

- (void)removeForkeyboardNotifications
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWasShow:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    float keyboardhight = 0;
    if(kbSize.height == 216)
    {
        keyboardhight = 0;
    }
    else
    {
        keyboardhight = kbSize.height-216;   //258 - 216 系统键盘的两个不同高度
    }
    //输入框位置动画加载
    inputTime = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    _emojiView.alpha = 0;
    emojiBt.selected = NO;
    [self onAnimationWithInputView:NO WithHeight:keyboardhight WithDuration:inputTime];
}

//当键盘隐藏的时候
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    //do something
    [self onAnimationWithInputView:YES WithHeight:0 WithDuration:inputTime];
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    [self onAnimationWithInputView:YES WithHeight:0 WithDuration:inputTime];
    
    //释放
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

//输入框和遮挡层动画效果
- (void)onAnimationWithInputView:(BOOL)isHidden WithHeight:(float)heght WithDuration:(float)time
{
    [UIView animateWithDuration:time animations:^{
        if (_emojiView.alpha == 0) {
            emojiBt.selected = NO;
            _emojiView.top = SCREEN_WIDTH;
            _inputView.top = (isHidden == YES ? SCREEN_HEIGHT : SCREEN_HEIGHT-216-heght-40);
            _inputView.hidden = isHidden;
            _showderView.hidden = isHidden;
            _showderView.height = _inputView.top;
        } else {
            emojiBt.selected = YES;
            _emojiView.top = SCREEN_HEIGHT - 216;
            _inputView.top = _emojiView.top-40;
            _inputView.hidden = NO;
            _showderView.height = _inputView.top;
            _showderView.hidden = NO;
        }
    } completion:^(BOOL finished) {
        if (finished) {
         //   _inputField.text = @"";
        }
    }];
}

- (void)onTapHideInputAction
{
    [_inputField resignFirstResponder];
    _emojiView.alpha = 0;
    emojiBt.selected = NO;
    [self onAnimationWithInputView:YES WithHeight:0 WithDuration:inputTime];
}

#pragma mark -表情
- (void)onSelectEmojiAction:(UIButton *)bt
{
    if (bt.selected == NO) {
        _emojiView.alpha = 1.f;
        [_inputField resignFirstResponder];
    } else {
        _emojiView.alpha = 0.f;
        [_inputField becomeFirstResponder];
    }
    
    //    bt.selected = !bt.selected;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    int lengthCount = (int)(textField.text.length + string.length);
    if (lengthCount >= 101) {
        return NO;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 回复
- (void)onSelectControlForReplyWithValue:(NSDictionary *)value withView:(MBSpaceNewsDetailCell *)view
{
    //响应键盘
    if ([value isKindOfClass:[NSDictionary class]]) {
        [_replyMutDic removeAllObjects];
        [_replyMutDic addEntriesFromDictionary:value];
    }
    
    //响应键盘
    if (_inputField) {
        _emojiView.alpha = 0;
        emojiBt.selected = NO;
        [_inputField becomeFirstResponder];
    }
}

//发送回复信息
- (void)onSelectSureAction
{
    [self onTapHideInputAction];
    
    UserModel *model = [UserManager standerDefult].userModel;
    if (_inputField.text.length == 0) {
        return;
    }
    if (!model)return;
    
    NSString *text = _inputField.text;
    NSString *uniStr = [NSString stringWithUTF8String:[text UTF8String]];
    NSData *uniData = [uniStr dataUsingEncoding:NSNonLossyASCIIStringEncoding];
    NSString *goodStr = [[NSString alloc] initWithData:uniData encoding:NSUTF8StringEncoding] ;
    
    [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FORUM_REPLY_INFO_URL_PATH,model.UserID,[_replyMutDic objectForKey:@"ID"],[_replyMutDic objectForKey:@"UserID"],goodStr] view:nil success:^(id json) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if ([json[@"ret_code"] integerValue]==0) {
            NSDate *date = [NSDate date];
            
            NSDictionary *nDic = @{@"ComID":[_replyMutDic objectForKey:@"ID"],
                                   @"CreateTime":[NSString stringWithFormat:@"%.f",[date timeIntervalSince1970]],
                                   @"ID":@"1",
                                   @"RepliedName":[_replyMutDic objectForKey:@"NickName"],
                                   @"ReplyCont":_inputField.text,
                                   @"ReplyName":model.NickName,
                                   @"ReplyImg":model.FaceImg,
                                   @"ToUserID":[_replyMutDic objectForKey:@"UserID"],
                                   @"UserID":model.UserID};
            NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:_replyMutDic];
            [mutDic setValue:nDic forKey:@"ReplyInfo"];
            int indexDic = (int)[_mutArr indexOfObject:_replyMutDic];
            //从选中的楼层中插入数据，数据显示在回复最底层
            indexDic = [self getReplyCengByData:(indexDic+1)];
            
            if (indexDic <= _mutArr.count && indexDic >= 0) {
                [_mutArr insertObject:mutDic atIndex:indexDic];
                
                //高度自定义
                [self onLoadDataForHeight];
                
                [_tableView reloadData];
            } else {
                if (_isFormMyNews) {
                    [self onLoadNew];
                }
            }
            [_replyMutDic removeAllObjects];
            _inputField.text = @"";
        } else {
            [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];

}

//从选中的楼层中插入数据，数据显示在回复最底层
- (int)getReplyCengByData:(int)selectIndexs
{
    if (selectIndexs < _mutArr.count && selectIndexs >= 0) {
        for (int i = selectIndexs;i < _mutArr.count; i++) {
            NSDictionary *dictionary = [_mutArr objectAtIndex:i];
            NSDictionary *dic = [dictionary objectForKey:@"ReplyInfo"];
            if ([dic isKindOfClass:[NSDictionary class]]) {
                if (dic.allKeys.count == 0) {
                    return i;
                }
            }
        }
        
        return (int)_mutArr.count;
    }
    else if (selectIndexs == _mutArr.count+1) {
        //最后一个没有回复的评论
        return selectIndexs;
    }
    return -1;
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _mutArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"News_Detail_Cell";
    MBSpaceNewsDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[MBSpaceNewsDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        cell.isFromShow=NO;
    }
    cell.orientation = self.orientation;
    
    if (_mutArr.count > indexPath.row) {
        NSDictionary *dic = [_mutArr objectAtIndex:indexPath.row];
        cell.dataDic = dic;
        cell.isShowUserNews = _isFormMyNews;
        //评论人ID
        if (_isFormMyNews == 0) {
            cell.zhuBoId = _taUserID;
        }
        NSString *taUserId = [dic objectForKey:@"UserID"];
        if ([taUserId isKindOfClass:[NSNull class]]) {
            cell.taUserId = @"0";
        } else {
            cell.taUserId = taUserId;
        }

        
        NSString *replay = [dic objectForKey:@"ReplyCont"];
        if ([replay isKindOfClass:[NSNull class]]) {
            cell.isHide = YES;
        } else if (replay.length == 0) {
            cell.isHide = YES;
        }
        else {
            cell.isHide = NO;
        }
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //测试
    if (_mutHeightArr.count > indexPath.row ) {
        
        return [[_mutHeightArr objectAtIndex:indexPath.row]floatValue];
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Emoji
- (void)onSelectItemForEmojiView:(NSString *)emoji withView:(EmojiView *)view
{
    if ([emoji isKindOfClass:[NSString class]]) {
        if (emoji.length > 0) {
            _inputField.text = [NSString stringWithFormat:@"%@%@",_inputField.text,emoji];
        }
    }
}

@end
